/*
 * Created on Jan 25, 2005
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.broadvision.manage.common.tools.action.common;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.util.MessageResources;

import com.broadvision.data.client.Content;
import com.broadvision.data.client.DataManager;
import com.broadvision.data.common.CallSettings;
import com.broadvision.data.common.CompoundKey;
import com.broadvision.data.common.ContentKey;
import com.broadvision.data.common.ContentUID;
import com.broadvision.data.common.DataAttributeList;
import com.broadvision.data.exceptions.DataException;
import com.broadvision.manage.tools.action.BaseAction;
import com.broadvision.portal.services.PortalVisitor;
import com.broadvision.web.action.Tab;
import com.broadvision.web.action.TabItem;
import com.broadvision.web.util.ViewDynaBean;

/**
 * @author kwlee
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public abstract class BasePickerPopupAction extends BaseAction {
  
  public static final String ITEM_DELIM = "$#@!";
  
  public static String PAGER_BEAN_NAME = "pager";
  public static String ITEM_VIEW_BEAN_NAME="mtItemView";
  
  public static String MULTI_SELECT = "MultiSelect";
                                              
  public static String BROWSE = "tab.browse";
  public static String SEARCH = "tab.search";
  public static String UNCATEGORIZED = "tab.uncategorized";
  
  public static String BROWSE_PATH = "mt.browse.path";
  public static String SEARCH_PATH = "mt.search.path";
  public static String UNCATEGORIZED_PATH = "mt.uncategorized.path";
  
  public static String NAME = "NAME";
  public static String OID = "OID";
  public static String CATEGORY_TABLE_NAME = "BV_CATEGORY";
  
  public static String DO_CLICK_ON_TAB = "mt.picker.popup.do.click.on.tab";
  
  public static String FILTER_INTERFACE_NAME = "mt.picker.popup.filter.interface.name";
  
  protected void fillUpUrlParams(Map urlParams, ActionForm form) throws Exception {
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    urlParams.put("contentTypeId", PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId").toString());
    urlParams.put("contentTypeName", PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeName").toString());
    urlParams.put("currentCategoryOid", PropertyUtils.getSimpleProperty(pickerPopupForm, "currentCategoryOid").toString());
    urlParams.put("currentCategoryName", PropertyUtils.getSimpleProperty(pickerPopupForm, "currentCategoryName"));
    
    // Don't need this parameter since the action itself already tells if it's multi select or not
//    if (((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "multiSelect")).booleanValue()) {
//      urlParams.put("multiSelect", "");
//    }// if

    Object selectedItemIds = PropertyUtils.getSimpleProperty(pickerPopupForm, "selectedItemIds");
    if (selectedItemIds != null && (selectedItemIds instanceof Long[]) && (((Long[])selectedItemIds).length != 0)) {
      Long[] iter = (Long[])selectedItemIds;
      StringBuffer selectedItemIdsStr = new StringBuffer();
      for (int i = 0; i < iter.length; i++) {
        if (i > 0) {
          selectedItemIdsStr.append(ITEM_DELIM);
        }// if
        selectedItemIdsStr.append(iter[i]);
      }// for
      urlParams.put("existingItemIds", selectedItemIdsStr.toString());
    }// if
    
    urlParams.put("callback", PropertyUtils.getSimpleProperty(pickerPopupForm, "callback"));
    
    if (((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "columnName")).length() != 0) {
      urlParams.put("columnName", PropertyUtils.getSimpleProperty(pickerPopupForm, "columnName"));
    }// if
    if (((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "searchKey")).length() != 0) {
      urlParams.put("searchKey", PropertyUtils.getSimpleProperty(pickerPopupForm, "searchKey"));
    }// if
    if (((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "allCategories")).booleanValue()) {
      urlParams.put("allCategories", "true");
    }// if
    urlParams.put("searchBtnNeverClicked", ((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "searchBtnNeverClicked")).toString());
    if (!((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "browseTab")).booleanValue()) {
      urlParams.put("browseTab", "false");
    }// if
    if (!((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "searchTab")).booleanValue()) {
      urlParams.put("searchTab", "false");
    }// if
    if (!((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "uncateTab")).booleanValue()) {
      urlParams.put("uncateTab", "false");
    }// if
    if (((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "cntFilterClass")).length() != 0) {
      urlParams.put("cntFilterClass", PropertyUtils.getSimpleProperty(pickerPopupForm, "cntFilterClass"));
    }// if
    if (((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "catFilterClass")).length() != 0) {
      urlParams.put("catFilterClass", PropertyUtils.getSimpleProperty(pickerPopupForm, "catFilterClass"));
    }// if
    if (((Integer)PropertyUtils.getSimpleProperty(pickerPopupForm, "minSelection")).intValue() != 1) {
      urlParams.put("minSelection", ((Integer)PropertyUtils.getSimpleProperty(pickerPopupForm, "minSelection")).toString());
    }// if
    if (!((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "rootSelection")).booleanValue()) {
      urlParams.put("rootSelection", "false");
    }// if
    if (((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "filterClassData")).length() != 0) {
      urlParams.put("filterClassData", PropertyUtils.getSimpleProperty(pickerPopupForm, "filterClassData"));
    }// if
    if (((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "searchBtnNeverClicked")).booleanValue()
        && ((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "defaultSearchResultIds")).length() != 0) {
      urlParams.put("defaultSearchResultIds", PropertyUtils.getSimpleProperty(pickerPopupForm, "defaultSearchResultIds"));
    }// if
    if (!((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "showAllCategories")).booleanValue()) {
      urlParams.put("showAllCategories", "false");
    }// if
  }
  
  /* (non-Javadoc)
   * @see com.broadvision.portal.tools.action.BaseAction#processExecute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  protected ActionForward processExecute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
    
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    if (pickerPopupForm == null || mapping == null) {
      request.setAttribute(Globals.ERROR_KEY, "error.application");
      return mapping.findForward("failure");
    }// if
    
    Object cntTypeIdObj = PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId");
    String cntTypeIdStr = cntTypeIdObj.toString();
    if (cntTypeIdStr == null || cntTypeIdStr.length() == 0) {
      request.setAttribute(Globals.ERROR_KEY, "mt.picker.popup.error.no.content.type.id");
      return mapping.findForward("success");
    }// if
    int cntTypeIdInt;
    try {
      cntTypeIdInt = Integer.parseInt(cntTypeIdStr);
      DataManager.getContentTypeInfo(cntTypeIdInt);
    }// try
    catch (NumberFormatException ex) {
      request.setAttribute(Globals.ERROR_KEY, "mt.picker.popup.error.content.type.id.not.number");
      return mapping.findForward("success");
    }// catch
    catch (DataException ex) {
      request.setAttribute(Globals.ERROR_KEY, "mt.picker.popup.error.no.valid.content.type.id");
      return mapping.findForward("success");
    }// catch
    
    String cntTypeName = DataManager.getContentTypeInfo(cntTypeIdInt).getFriendlyName();
    PropertyUtils.setSimpleProperty(pickerPopupForm, 
                                    "contentTypeName", 
                                    cntTypeName);

    
/*** Get the parameter specified from strut-config-mt.xml*/

    // Get multiple selection flag
    String parameter = mapping.getParameter();
    if (parameter != null && parameter.equals("multiSelect")) {
      PropertyUtils.setSimpleProperty(pickerPopupForm, 
                                      "multiSelect", 
                                      new Boolean(true));
    }// if
    
    // Set selectedTab
    PropertyUtils.setSimpleProperty(pickerPopupForm, 
                                    "selectedTab", 
                                    String.valueOf(getTabPageIndex()));
                                    
    String existingItemIds = (String)PropertyUtils.getSimpleProperty(pickerPopupForm, "existingItemIds");
      
    if (existingItemIds.length() != 0) {
      List itemsIdList = new ArrayList();
      StringTokenizer st = new StringTokenizer(existingItemIds, ITEM_DELIM);
      while (st.hasMoreTokens()) {
        String token = st.nextToken();
        try {
          Long id = new Long(token);
          if (isValidId(getServiceId(request), cntTypeIdInt, id.longValue()))
            itemsIdList.add(id);
        }// try
        catch (NumberFormatException ex) {
          continue;
        }// catch
      }// while
      if (itemsIdList.size() != 0) {
        List itemsNameList = getItemsNameList(mapping, form, request, response, itemsIdList);
        if (itemsNameList.size() != 0) {
          PropertyUtils.setSimpleProperty(pickerPopupForm, 
                                          "selectedItemIds",
                                          itemsIdList.toArray(new Long[0]));
          PropertyUtils.setSimpleProperty(pickerPopupForm, 
                                          "selectedItemNames",
                                          itemsNameList.toArray(new String[0]));
        }// if
      }// if
    }// if

    prepareTabPages(mapping, form, request, response);
                                      
    return doProcessExecute(mapping, form, request, response);
  }
  
  protected String[][] getTabPageMap(HttpServletRequest request) {
    String[][] tabPageMap = {{getMessage(request, BROWSE), getMessage(request, BROWSE_PATH), "browseTab"},
                             {getMessage(request, SEARCH), getMessage(request, SEARCH_PATH), "searchTab"},
                             {getMessage(request, UNCATEGORIZED), getMessage(request, UNCATEGORIZED_PATH), "uncateTab"}};
    return tabPageMap;
  }
  
  protected void prepareTabPages(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) 
                                throws Exception {
    Tab tab = new Tab();
    request.setAttribute("pagetab", tab);
    
    // Get the selected tab page index    
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    int selectedTab = getTabPageIndex();
    String[][] tabPageMap = getTabPageMap(request);
    
    TabItem tabItem = null;
    int count = tabPageMap.length;
    for (int i = 0; i < count; i++) {
      boolean tabNeeded = ((Boolean)PropertyUtils.
                                  getSimpleProperty(pickerPopupForm, tabPageMap[i][2])).booleanValue();
      
      if ((!tabNeeded) && (i != selectedTab)) {
        continue;
      }// if
      
      String path = tabPageMap[i][1];
      if (((Boolean)PropertyUtils.
              getSimpleProperty(pickerPopupForm, "multiSelect")).booleanValue()) {
        path = path + MULTI_SELECT;
      }// if
      path = request.getContextPath() + path + ".do";
      path = response.encodeURL(path);
      tabItem = new TabItem(tabPageMap[i][0], "");
      tabItem.setOnclick(getMessage(request, DO_CLICK_ON_TAB) 
                                    + "('"
                                    + path
                                    + "');");     
      tabItem.setSelected(selectedTab == i);
      tab.addItem(tabItem);
    }// for
    // Make the tab invisible if there is only one tab
    if (tab.getItems().size() == 1) {
      tab.disable();
      ((TabItem)tab.getItems().get(0)).setVisible(false);
    }// if
  }
  
  protected ActionForward doProcessExecute(ActionMapping mapping, 
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) 
                        throws Exception {


    String parameter = request.getParameter("pager.offset");
    boolean newList = (parameter == null);
    int offset = (parameter == null) ? 0 : Integer.parseInt(parameter);
    parameter = request.getParameter("pager.maxPageItems");
    int maxPageItems = (parameter == null) ? 10 : Integer.parseInt(parameter);
 
//   List results = null;
//   if (newList) {
//     results = getList(mapping, form, request, response);
//     request.getSession().setAttribute(LIST_RESULT_ATT_NAME, results);
//   }
//   else {
//     results = (List)request.getSession().getAttribute(LIST_RESULT_ATT_NAME);
//     if (results == null) {
//       results = getList(mapping, form, request, response);
//       request.getSession().setAttribute(LIST_RESULT_ATT_NAME, results);        
//     }      
//   }
//   if (offset >= results.size()) {
//     offset = 0;
//   }

    List results = getList(mapping, form, request, response);
    
    // Perform filtering
    results = doItemsListFiltering(mapping, form, request, response, results);
    
    int count = results.size();
    if (offset >= count) {
      offset = 0;
    }// if
  
   List list = new ArrayList();
   request.setAttribute("list", list);
   String columnName = getColumnName(mapping, form, request, response);
   for (int i = 0, index = offset; i < maxPageItems && index < count; i++, index++) {
     ViewDynaBean dto = new ViewDynaBean(ITEM_VIEW_BEAN_NAME, mapping);
     Content cnt = null;
     Object item = results.get(index);
     if (item instanceof PickerFilterHelper) {
       PickerFilterHelper helper = (PickerFilterHelper)item;
       if (helper.getContent() instanceof Content) {
         PropertyUtils.setSimpleProperty(dto, "canSelect", new Boolean(helper.isCanSelect()));
         cnt = (Content)helper.getContent();
       }// if
       else {
          continue;
       }// else
     }// if
     else if (item instanceof Content) {
       cnt = (Content)item;
     }// else
     else {
       continue;
     }// else
     fillUpItemBean(mapping, form, request, response, dto, cnt, columnName);
     list.add(dto);
   }
   ViewDynaBean pager = new ViewDynaBean(PAGER_BEAN_NAME, mapping);
   request.setAttribute(PAGER_BEAN_NAME, pager);
   PropertyUtils.setSimpleProperty(pager, "url",  mapping.getPath() + ".do");
   PropertyUtils.setSimpleProperty(pager, "count", new Integer(count));
   PropertyUtils.setSimpleProperty(pager, "maxPageItems", new Integer(maxPageItems));
   Map urlParams = new HashMap();
   if (count != 0) {
     fillUpUrlParams(urlParams, form);
   }// if
   PropertyUtils.setSimpleProperty(pager, "urlParams", urlParams);
   return mapping.findForward("success");
  }
  public abstract List getList(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, 
                                HttpServletResponse response) throws Exception;
   
  public void fillUpItemBean(ActionMapping mapping, ActionForm form,
                      HttpServletRequest request, HttpServletResponse response, 
                      ViewDynaBean viewBean, Object item, String columnName) throws Exception {    
    PropertyUtils.setSimpleProperty(viewBean, "id", new Long(((Content)item).getOid()));
    PropertyUtils.setSimpleProperty(viewBean, "name", getDisplayName(item, columnName));
    PropertyUtils.setSimpleProperty(viewBean, "nameToSave", getDisplayName(item, columnName));
  }
  
  public abstract int getTabPageIndex();
  
  public String getColumnName(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request, 
                              HttpServletResponse response) throws Exception {
                                
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    return PropertyUtils.getSimpleProperty(pickerPopupForm, 
                                                      "columnName").toString();
  }
  
  protected String getMessage(HttpServletRequest request, String key) {
    Locale locale = getLocale(request);
    MessageResources resources = getResources(request, "mt.messages");
    String message = resources.getMessage(locale, key);
    return message;
  }
  
  protected List getItemsNameList(ActionMapping mapping, ActionForm form,
                                  HttpServletRequest request, 
                                  HttpServletResponse response, 
                                  List itemsIdList) throws Exception {
    // Get the content type id
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    int cntTypeId = Integer.parseInt((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));

    // Create a long[] which contains item ids
    long[] itemsIdArray = new long[itemsIdList.size()];
    HashMap itemsIdMap = new HashMap();
    for (int i = 0; i < itemsIdList.size(); i++) {
      itemsIdArray[i] = ((Long)itemsIdList.get(i)).longValue();
      itemsIdMap.put((Long)itemsIdList.get(i), new Integer(i));
    }// for
    
    // Try to get the column name. If no column name specified, get the key.
    // The key can be single or compound key
    String columnName = getColumnName(mapping, form, request, response);
    List keyNames = null;
      
    if (columnName != null && columnName.length() != 0) {
      keyNames = new ArrayList(1);
      keyNames.add(columnName);
    }// if
    else {
      DataAttributeList attriList = DataManager.getAttributes(cntTypeId, 
                                                              getServiceId(request));
      keyNames = attriList.getKeyNames();
    }// if
    
    // Create an attribute list
    ArrayList attributesList = new ArrayList(keyNames);
    attributesList.add(OID);
    
    // TODO: Before getting the partial contents, do we need to call contentExists()
    //        for each item id to check if they exist in the system?
    // Get partial contents
    DataManager dm = new DataManager();
    CallSettings callsettings = dm.getCallSettings();
    callsettings.setFilteringFlag(false);

    List cntItemsList = dm.getPartialContents(cntTypeId, getServiceId(request),
                                              itemsIdArray, attributesList);
                                              
    // Create a list which contains a list of display name
    int theSize = cntItemsList.size();
    List returnList = new ArrayList(theSize);
    for (int j = 0; j < theSize; j++) {
      returnList.add("");
    }
    for (int j = 0; j < theSize; j++) {
      Long theOid = new Long(((Content)(cntItemsList.get(j))).getOid());
      int theIndex = ((Integer)(itemsIdMap.get(theOid))).intValue();
      if (theIndex >= 0 && theIndex < theSize)
        returnList.set(theIndex, getDisplayName(cntItemsList.get(j), columnName));
    }// for
    
    return returnList;
  }
  
  protected String getDisplayName(Object item, String columnName) throws Exception {
    String displayName = "";
    if (columnName == null || columnName.length() == 0) {
      ContentKey cntKey = ((Content)item).getKey();
      if (cntKey instanceof CompoundKey) {
        displayName = ((CompoundKey)cntKey).keyValueString();
      }// if
      else {
        displayName = cntKey.getKey().toString();
      }// else
    }// if
    else {
      displayName = ((Content)item).getStringValue(columnName);
    }// else
    return displayName;
  }
  
  protected boolean isValidId(int serviceId, int contentTypeId, long id) {
    ContentUID uid = new ContentUID(contentTypeId, serviceId, id);
    boolean result = false;
    try {
      DataManager dm = new DataManager();
      CallSettings callsettings = dm.getCallSettings();
      callsettings.setFilteringFlag(false);
      result = dm.contentExists(uid);
    }// try
    catch (DataException ex) {
    }// catch
    return result;
  }

  protected List doItemsListFiltering(ActionMapping mapping, ActionForm form,
                                      HttpServletRequest request, 
                                      HttpServletResponse response,
                                      List listToBeFiltered){
    try {
      return doListFiltering(mapping, form, request, response, listToBeFiltered, true);
    }// try
    catch (Exception ex) {
      System.out.println("doItemsListFiltering() failed. Reason:" 
                          + ex.getClass().getName()
                          + " No filtering performed for items list.");
      return listToBeFiltered;
    }// catch
  }
  
  protected List doCatListFiltering(ActionMapping mapping, ActionForm form,
                                            HttpServletRequest request, 
                                            HttpServletResponse response,
                                            List listToBeFiltered){
    try {
      return doListFiltering(mapping, form, request, response, listToBeFiltered, false);
    }// try
    catch (Exception ex) {
      System.out.println("doCatListFiltering() failed. Reason:" 
                          + ex.getClass().getName()
                          + " No filtering performed for categories list.");
      return listToBeFiltered;
    }// catch
  }
  
  protected final List doListFiltering(ActionMapping mapping, ActionForm form,
                                      HttpServletRequest request, 
                                      HttpServletResponse response,
                                      List listToBeFiltered, boolean cntOrCat) throws Exception {
//    System.out.println("doListFiltering() - cntOrCat is " + cntOrCat);
    // No need to do filtering if the listToBeFiltered is empty
    if (listToBeFiltered.size() == 0) {
      return listToBeFiltered;
    }// if

    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    String className = PropertyUtils.getSimpleProperty(pickerPopupForm, 
                            (cntOrCat ? "cntFilterClass" : "catFilterClass")).toString();
    if (className == null || className.length() == 0) {
      return listToBeFiltered;
    }// if
    
    long cntTypeId = Long.parseLong((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));
    
    String optionalData = (String)PropertyUtils.getSimpleProperty(pickerPopupForm, "filterClassData");
    
//    System.out.println("\nBefore filtering: #####################################");
//    for (int i = 0; i < listToBeFiltered.size(); i++) {
//      System.out.println(((Content)listToBeFiltered.get(i)).getStringValue("NAME"));
//    }// for
//    System.out.println("#####################################");
    List resultList = performFiltering(request, cntTypeId, getPortalVisitor(request), 
                      className, listToBeFiltered,
                      optionalData.length() == 0 ? null : optionalData);
//    System.out.println("\nAfter filtering: **************************************");
//    for (int j = 0; j < resultList.size(); j++) {
//      Object item = resultList.get(j);
//      Content cnt = null;
//      if (item instanceof PickerFilterHelper) {
//        PickerFilterHelper helper = (PickerFilterHelper)item;
//        if (helper.getContent() instanceof Content) {
//          cnt = (Content)helper.getContent();
//        }// if
//        else {
//           continue;
//        }// else
//      }// if
//      else if (item instanceof Content) {
//        cnt = (Content)item;
//      }// else
//      else {
//        continue;
//      }// else
//      System.out.println(cnt.getStringValue("NAME"));
//    }// for
//    System.out.println("**************************************\n");
    return resultList;
  }

  protected final List performFiltering(HttpServletRequest request, long cntTypeId, 
                                        PortalVisitor portalVisitor, 
                                        String className, 
                                        List listToBeFiltered,
                                        String optionalData) throws Exception {
    // Create an instance of the filter class
    Class cls = Class.forName(className);
    Object clsObj = cls.newInstance();
    
    // Create a Class object of the interface that we defined
    Class itrfc = Class.forName(getMessage(request, FILTER_INTERFACE_NAME));
    Method[] meths = itrfc.getMethods(); // Assume that the interface only has one method
    
    
    Class partypes[] = new Class[5];
    partypes[0] = Integer.TYPE;
    partypes[1] = Long.TYPE;
    partypes[2] = PortalVisitor.class;
    partypes[3] = List.class;
    partypes[4] = String.class;
    Method meth = cls.getMethod(meths[0].getName(), partypes); // Assume that the interface only has one method
    
    Object arglist[] = new Object[5];
    arglist[0] = new Integer(getServiceId(request));
    arglist[1] = new Long(cntTypeId);
    arglist[2] = portalVisitor;
    arglist[3] = listToBeFiltered;
    arglist[4] = optionalData;
    Object retobj = meth.invoke(clsObj, arglist);

    return (List)retobj;
  }
}
